var bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({
    extended: false
})
var express = require('express')
var db = require('../bd.js')
var router = express.Router()
const md5 = require('md5-nodejs');


// 登录注册
router.post("/applogin", urlencodedParser, async (req, res) => {
    let { name, loginName } = req.body
    let sql = `select * from appuser where loginName = '${loginName}'`
    let r = await db.doSQL(sql)
    if (r.length) {  // 已注册 直接去找token
        // console.log(r[0].id)
        let token = await tost(r[0].id)
        res.send(db.handerResult(token))
    } else {
        let sql1 = `insert into appuser (name,loginName)  values ('${name}','${loginName}')`
        let r = await db.doSQL(sql1)
        if (r.affectedRows) {  // 添加（注册） 成功就去添加token
            let sql2 = `select id from appuser where loginName = '${loginName}'`
            let r = await db.doSQL(sql2)
            let token = await tost(r[0].id)
            res.send(db.handerResult(token))
        } else {  // 没有注册成功
            res.send(db.error(r))
        }
    }
})

// 添加token
// 拿去MD5  或 创建MD5
function tost(uid) {
    let sql = `select * from appTokens where uid='${uid}'`
    return new Promise((relv, recj) => {
        db.doSQL(sql).then(res => {
            let data
            if (res.length && res[0].token) {
                data = res[0].token
            } else {
                // console.log("创建")
                data = md5("zxwx" + uid)
                // 创建完成后的存储
                saveTost(data, uid)
            }
            relv(data)
        })
    })
}

// 创建函数  token 添加
async function saveTost(token, uid) {
    let sql = `insert into appTokens (token,uid) values ('${token}',${uid})`;
    const data = await db.doSQL(sql)
}

// 用token去取数据
router.get("/takeinfo", async function (req, res) {
    let { token } = req.query;
    let sql = `select * from appTokens as t,appuser as u where t.uid=u.id and t.token='${token}'`
    let r = await db.doSQL(sql)
    res.send(db.handerResult(r))
})

// 用uid 获取name头像
router.get("/getinfo", async function (req, res) {
    let { id } = req.query;
    let sql = `select * from appuser where id=${id}`
    let r = await db.doSQL(sql)
    res.send(db.handerResult(r))
})

module.exports = router;